package cn.flying.cloud.core.auth.service;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

/**
 * @description: 用户权限校验服务
 * @author: admin
 * @date: 2023年05月29日 00:26
 * @version: 1.0
 */
@Component("rbacService")
public class RbacService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 验证访问的url是否权限
     *
     * @param request
     * @param authentication
     * @return true 验证通过
     */
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) principal;

            //将请求的uri包装成授权资源对象
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(request.getRequestURI());
            return userDetails.getAuthorities().contains(authority);
        }

        return false;
    }
}
